package org.example.learn;

/**
 * 二分查找的例子
 */
public class BiSearch {

    public static void main(String[] args) {

        int[] array={1,2,3,4,5,6,7};
        int index=biSearch(array,6);
        System.out.println("位置是:"+index);

    }

    private static  int biSearch(int[] array,int a){
        int lo=0;
        int hi=array.length-1;

        int mid;

        while (lo<=hi){
            // 中间位置
            mid=(lo+hi)/2;
            if(array[mid]==a){
                return mid+1;
                //向右查找
            }else if(array[mid]<a){
                lo=mid+1;
            }else {
                //向左查找
                hi=mid-1;
            }
        }
        return -1;
    }

}
